import { defineStore } from 'pinia'

const STORAGE_TOKEN_KEY = 'token'
const STORAGE_ROLE_KEY = 'userRole'
const STORAGE_USER_KEY = 'user'

export const useAuthStore = defineStore('authStore', {
  state: () => ({
    token: /** @type {string | null} */ (null),
    role: /** @type {'student' | 'teacher' | 'admin' | null} */ (null),
    user: /** @type {Record<string, any> | null} */ (null),
  }),
  getters: {
    isAuthenticated: (state) => !!state.token,
    isStudent: (state) => state.role === 'student',
    isTeacher: (state) => state.role === 'teacher',
    isAdmin: (state) => state.role === 'admin',
  },
  actions: {
    /**
     * 登录：保存 token 与 role，并持久化到 sessionStorage
     * @param {{ token: string, role: 'student'|'teacher'|'admin', user?: Record<string, any> }} payload
     */
    login(payload) {
      this.token = payload.token
      this.role = payload.role
      this.user = payload.user ?? null

      sessionStorage.setItem(STORAGE_TOKEN_KEY, this.token)
      sessionStorage.setItem(STORAGE_ROLE_KEY, this.role)
      if (this.user) sessionStorage.setItem(STORAGE_USER_KEY, JSON.stringify(this.user))
    },

    /**
     * 启动恢复：从 sessionStorage 复原
     */
    restore() {
      const token = sessionStorage.getItem(STORAGE_TOKEN_KEY)
      const role = sessionStorage.getItem(STORAGE_ROLE_KEY)
      const userStr = sessionStorage.getItem(STORAGE_USER_KEY)
      this.token = token || null
      this.role = role === 'student' || role === 'teacher' || role === 'admin' ? role : null
      this.user = userStr ? JSON.parse(userStr) : null
    },

    /**
     * 登出：清理并重定向到 /login（由调用方或路由守卫执行重定向）
     */
    logout() {
      this.token = null
      this.role = null
      this.user = null
      sessionStorage.removeItem(STORAGE_TOKEN_KEY)
      sessionStorage.removeItem(STORAGE_ROLE_KEY)
      sessionStorage.removeItem(STORAGE_USER_KEY)
    },
  },
})
